from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import images

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.paginator import Paginator, InvalidPage, EmptyPage

from itertools import chain

from content.forms import PublicationForm, IssueForm, CreateArticleForm, EditArticleForm, ImageForm
from content.models import Issue, Publication, Article, Image
from people.models import Invite
from helpers.misc import new_skey
from helpers.choices import OBJ_HANDLER

def publication_add(request, key):
	if not request.method == 'POST':
		form = PublicationForm()
		return render_to_response('content/publication/add.html', {'form': form})
	
	form = PublicationForm(request.POST)
	if not form.is_valid():
		return render_to_response('content/publication/error.html')

	if form.save().save():
		return render_to_response('content/publication/add.html', {'form': form})
	return render_to_response('content/publication/error.html')

def publication_edit(request, key):
	publication = Publication.all().filter('s_key =', key)[0]
	if not publication.can_edit():
        	return render_to_response('content/publication/error.html')

	if not request.method == 'POST':
		form = PublicationForm(instance=publication)
		return render_to_response('content/publication/add.html', {'form': form})
	
	form = PublicationForm(request.POST,instance=publication)
	if not form.is_valid():
		return render_to_response('content/publication/error.html')
	if form.save():
		return render_to_response('content/publication/add.html', {'form': form})
	return render_to_response('content/publication/error.html')


def publication_remove(request, key):
	publication = Publication.all().filter('s_key =', key)[0]
	if not publication.is_owner():
        	return render_to_response('content/publication/error.html')

	if not request.method == 'POST':
		form = PublicationForm(instance=publication)
		return render_to_response('content/publication/add.html', {'form': form})
	
	form = PublicationForm(request.POST,instance=publication)
	if not form.is_valid():
		return render_to_response('content/publication/error.html')
	publication = form.save()
	if publication.save():
		return render_to_response('content/publication/add.html', {'form': form})
	return render_to_response('content/publication/error.html')

def issue_add(request, key):
	if not request.method == 'POST':
		form = IssueForm()
		return render_to_response('content/issue/add.html', {'form': form})
	data = {}
	data['publication'] = Publication.get(request.POST.get('publication'))
	data['title'] = request.POST.get('title')
	data['number'] = request.POST.get('number')
	form = IssueForm(request.POST)
	if form.create(data):
		return render_to_response('content/issue/add.html', {'form': form})
       	return render_to_response('content/issue/error.html')

def issue_edit(request, key):
	if not issue.can_edit():
        	return render_to_response('content/issue/error.html')

	#FIXME: Show 'Publication' selected 
	form = IssueForm(instance=issue)
	if not request.method == 'POST':
		return render_to_response('content/issue/add.html', {'form': form})
	issue.publication = Publication.get(request.POST.get('publication'))

	issue.title = request.POST.get('title')
	issue.number = int(request.POST.get('number'))

	if issue.save():
		return render_to_response('content/issue/add.html', {'form': form})
       	return render_to_response('content/issue/error.html')

def issue_view(request, key):
	issue = Issue.all().filter('s_key =', key)[0]
	publication = issue.publication
	if not issue.can_view() and not publication.can_view():
       		return render_to_response('content/issue/error.html')
	articles = Article.all().filter('parents =', issue.key())
	data={}
	data={'articles': articles, 
		'publication': publication,
		'issue': issue,
		}
	return render_to_response('content/issue/view.html', data)


def issue_remove(request, key):
	issue = Issue.all().filter('s_key =', key)[0]
	if not issue.is_owner():
        	return render_to_response('content/issue/error.html')

	form = IssueForm(instance=issue)
	if not request.method == 'POST':
		return render_to_response('content/issue/add.html', {'form': form})

	issue.author = None
	issupe.publication = Publication.all().filter('s_key =', key).get(request.POST.get('publication'))
	issue.title = request.POST.get('title')
	issue.number = int(request.POST.get('number'))
	issue.status = False
	if not issue.save():
        	return render_to_response('content/issue/error.html')
	form = IssueForm(instance=issue)
	return render_to_response('content/issue/add.html', {'form': form})

def article_add(request, key):
	if not request.method == 'POST':
		form = CreateArticleForm()
		return render_to_response('content/article/add.html', {'form': form})

	data = {}
	data['parents'] = []
	for x in request.POST.getlist('issue'):
		data['parents'].append(db.Key(x))
	for x in request.POST.getlist('publication'):
		data['parents'].append(db.Key(x))

	if request.POST.get('public'):
		data['public'] = True
	else:
		data['public'] = False
		
	data['tags'] = []
	for x in request.POST.get('tags').split(','):
		data['tags'].append(x)
	data['title'] = request.POST.get('title')
	form = CreateArticleForm()

	if form.create(data):
		return render_to_response('content/article/add.html', {'form': form})
       	return render_to_response('content/article/error.html')

def article_edit(request, key):
	article = Article.all().filter('s_key =', key)[0]
	if not article.can_edit():
        	return render_to_response('content/article/error.html')

	form = EditArticleForm(instance=article)

	invites = Invite.all().filter('entry =', article)
	if not request.method == 'POST':
		return render_to_response('content/article/add.html', {'form': form, 'invites': invites})
	data = {} 
	data['parents'] = []
	for x in request.POST.getlist('issue'):
		data['parents'].append(db.Key(x))
	for x in request.POST.getlist('publication'):
		data['parents'].append(db.Key(x))

	if request.POST.get('public'):
		article.public = True
	else:
		article.public = False
		
	tags = []
	for x in request.POST.get('tags').split(','):
		tags.append(x)
	article.tags = tags
	article.title = request.POST.get('title')
	article.content = request.POST.get('content')

	if article.save():
		return render_to_response('content/article/add.html', {'form': form, 'invites': invites})

       	return render_to_response('content/article/error.html')

def article_remove(request, key):
	article = Article.all().filter('s_key =', key)[0]
	if not article.is_owner():
        	return render_to_response('content/article/error.html')
	if not request.method == 'POST':
		return render_to_response('content/article/error.html', {'form': form})
	article.status = False
	if article.save():
		return render_to_response('content/article/add.html', {'form': form})
       	return render_to_response('content/article/error.html')


def image_add(request, key):
	if not request.method == 'POST':
		return render_to_response('content/image/error.html')
	img_file=request.FILES['upload'].read()
	image = Image(image=db.Blob(img_file), title=request.FILES['upload'].name, thumbnail=db.Blob(images.resize(img_file, 64)))
	if image.save():
		return render_to_response('content/image/added.html')
	return render_to_response('content/image/error.html')

def image_view(request, key):
	image = Image.all().filter('s_key =', key)[0]
	if not image.can_view():
		return render_to_response('content/image/error.html')
	return HttpResponse(image.image,'image')

def t_image_view(request, key):
	image = Image.all().filter('s_key =', key)[0]
	if not image.can_view():
		return render_to_response('content/image/error.html')
	return HttpResponse(image.thumbnail,'image')

def browse(request, obj, page=1, qtd=25):
	#TODO: show the pages as clickable links
	user = users.get_current_user()
	if user:
		entries_list = list(chain(OBJ_HANDLER[obj].objects.all().filter('public =', False).filter('status >', 0).filter('author =', user), OBJ_HANDLER[obj].objects.all().filter('public =', True)))

	else:
		entries_list = OBJ_HANDLER[obj].objects.all().filter('public =', True)
	paginator = Paginator(entries_list, int(qtd))
	try:
		entries = paginator.page(page)
	except (EmptyPage, InvalidPage):
		entries = paginator.page(paginator.num_pages)
	return render_to_response('content/browse/index.html', {"entries": entries, 'obj': obj})
